package api

import (
	"github.com/gogf/gf/net/ghttp"
	"myGo/app/model"
	"myGo/app/service"
	"myGo/library/response"
)

var User = userApi{}

type userApi struct {
}

// Index is a demonstration route handler for output "Hello World!".
func (user *userApi) Index(r *ghttp.Request) {
	ctx := r.GetCtx()
	if res, err := service.User.GetList(ctx); err != nil {
		response.JsonExit(r, 1, "获取失败", err)
	} else {
		response.JsonExit(r, 0, "获取成功", res)
	}
}

func (user *userApi) Create(r *ghttp.Request) {
	ctx := r.GetCtx()
	var (
		serviceReq *model.UserServiceSignUpReq
	)
	if err := r.ParseForm(&serviceReq); err != nil {
		response.JsonExit(r, 1, err.Error())
	}

	if err := service.User.Create(ctx, serviceReq); err != nil {
		response.JsonExit(r, 1, "添加失败", err)
	} else {
		response.JsonExit(r, 0, "添加成功")
	}
}

func (user *userApi) Update(r *ghttp.Request) {
	ctx := r.GetCtx()
	var (
		serviceReq *model.UserServiceUpdateReq
	)
	if err := r.ParseForm(&serviceReq); err != nil {
		response.JsonExit(r, 1, err.Error())
	}

	if err := service.User.Update(ctx, serviceReq); err != nil {
		response.JsonExit(r, 1, "编辑失败", err)
	} else {
		response.JsonExit(r, 0, "编辑成功")
	}
}

func (user *userApi) Info(r *ghttp.Request) {
	ctx := r.GetCtx()
	id := r.GetRequestInt("id")
	if info, err := service.User.Info(ctx, id); err != nil {
		response.JsonExit(r, 1, "查询失败")
	} else {
		response.JsonExit(r, 0, "查询成功", info)
	}
}

func (user *userApi) Delete(r *ghttp.Request) {
	ctx := r.GetCtx()
	id := r.GetRequestInt("id")
	if err := service.User.Delete(ctx, id); err != nil {
		response.JsonExit(r, 1, "删除失败", err)
	} else {
		response.JsonExit(r, 0, "删除成功")
	}
}

func (user *userApi) List(r *ghttp.Request) {
	ctx := r.GetCtx()
	if res, err := service.User.GetList(ctx); err != nil {
		response.JsonExit(r, 1, "获取失败", err)
	} else {
		response.JsonExit(r, 0, "获取成功", res)
	}
}